<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import type { Goods } from '@/types/goods'
import { getGoodsDetail } from '@/api/goods'
import { ref, watch } from 'vue'
import { useCartStore } from '@/store/cart'
const store = useCartStore()

const goods = ref({} as Goods)

onLoad(async (options: any) => {
  const res = await getGoodsDetail(options.proid)
  goods.value = res.data

  uni.setNavigationBarTitle({
    title: res.data.proname
  })
})

// 实现图片预览
const preview = (current: number) => {
  uni.previewImage({
    current,
    urls: goods.value.banners[0].split(',')
  })
}
const options = ref([
  {
    icon: 'headphones',
    text: '客服'
  },
  {
    icon: 'shop',
    text: '店铺'
  },
  {
    icon: 'cart',
    text: '购物车',
    info: store.getTotal
  }
])

watch(
  () => store.getTotal,
  newValue => {
    ;(options.value![2] as any).info = newValue
  }
)

const buttonGroup = [
  {
    text: '加入购物车',
    backgroundColor: '#ff0000',
    color: '#fff'
  },
  {
    text: '立即购买',
    backgroundColor: '#ffa200',
    color: '#fff'
  }
]

const onClick = (e: any) => {
  if (e.index === 2) {
    uni.switchTab({
      url: '/pages/cart/index'
    })
  }
}
const buttonClick = (e: any) => {
  if (e.index === 0) {
    const goodsObj = {
      proid: goods.value.proid,
      proname: goods.value.proname,
      img: goods.value.img1,
      num: 1,
      price: goods.value.originprice,
      state: true // 默认选中
    }

    // 调用仓库的方法，保存到仓库中
    store.addToCart(goodsObj)

    uni.showToast({
      icon: 'success',
      title: '加入购物车成功'
    })
  }
}
</script>

<template>
  <view v-if="goods.banners">
    <swiper autoplay circular indicator-dots>
      <swiper-item
        v-for="(item, index) in goods.banners[0].split(',')"
        :key="index"
      >
        <image :src="item" @click="preview(index)" />
      </swiper-item>
    </swiper>
    <!-- 详情区域 -->
    <view class="info">
      <van-tag type="danger" size="large">自营</van-tag>
      <text>{{ goods.proname }}</text>
      <view class="price">￥{{ goods.originprice }}</view>
    </view>
    <!-- 底部导航区域 -->
    <uni-goods-nav
      style="position: fixed; bottom: 0; left: 0; right: 0"
      :fill="true"
      :options="options"
      :buttonGroup="buttonGroup"
      @click="onClick"
      @buttonClick="buttonClick"
    />
  </view>
</template>

<style lang="scss" scoped>
swiper {
  height: 700rpx;
}

.info {
  padding: 10px;
  .price {
    font-size: 20px;
    color: red;
    font-weight: bold;
  }
}
</style>
